﻿using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace KstopaCommon
{
    public static class IniFileOperator
    {
        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileString(string section, string key, string strDefault, StringBuilder retVal, int size, string filename);

        [DllImport("kernel32.dll")]
        private static extern long WritePrivateProfileString(string section, string key, string value, string filename);

        public static bool ReadIniString(string section, string key, string filename, ref string value, ref string msg)
        {
            if (File.Exists(filename) == false)
            {
                msg = "读取的INI文件不存在";
                return false;
            }
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                GetPrivateProfileString(section, key, "", stringBuilder, 256, filename);
                value = stringBuilder.ToString();
                return true;
            }
            catch
            {
                msg = "INI文件读取异常(" + section + ":" + key + ")";
                return false;
            }
        }

        public static bool WriteIniString(string section, string key, string value, string filename, ref string msg)
        {
            if (File.Exists(filename) == false)
            {
                msg = "写入的INI文件不存在";
                return false;
            }
            try
            {
                WritePrivateProfileString(section, key, value, filename);
                return true;
            }
            catch
            {
                msg = "INI文件写入异常(" + section + ":" + key + ")";
                return false;
            }
        }

    }
}
